class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        int left = n;
        int right = n;
        dfs(list, new StringBuilder(), left, right);
        return list;
        
    }
    public void dfs(List<String> list, StringBuilder sb, int left, int right){
        if(left == 0 && right == 0){
            list.add(sb.toString());
            return;
        }
        if(left > 0){
            sb.append("(");
            dfs(list, sb, left-1, right);
            sb.deleteCharAt(sb.length() - 1);
        }
        if(right > 0 && right > left){
            sb.append(")");
            dfs(list, sb, left, right-1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

}